package com.xbjtech.vipsystem.shiro;

import com.xbjtech.vipsystem.po.User;
import com.xbjtech.vipsystem.utils.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-23
 */
public class JwtRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

//        info.addStringPermission("");
//        info.addRole("");

        return info;
    }

    /**
     * 获取正确的认证信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (authenticationToken instanceof JwtToken) {
            JwtToken jwtToken = (JwtToken) authenticationToken;
            String token = jwtToken.getToken();
            boolean verify = JwtUtils.verify(token);
            if (verify == false) {
                throw new AuthenticationException("token不合法");
            }
            User user = JwtUtils.getUserFromToken(token);
            return new SimpleAuthenticationInfo(user, token, getName());
        }
        return null;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
